package com.xianyun.book.domain.book;

import com.xianyun.book.domain.common.CountEnum;
import com.xianyun.book.domain.order.Order;
import com.xianyun.book.domain.order.OrderStatus;
import com.xianyun.book.domain.price.Currency;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author ytt
 */
@Slf4j
@Data
public class Book {
    private Integer id;
    private String bookId;
    private String bookName;
    private List<BookType> bookTypes;
    private BookFineness fineness;
    private String imgUrl;
    private BookStatus bookStatus;
    private String author;
    private String press;
    /**参与人数*/
    private Integer personNumber;
    /**评论分数*/
    private Double score;
    /**ISBN码*/
    private String isbn;
    /**库存量*/
    private Integer inStock;
    private String publishDate;
    /**上新时间*/
    private Date newTime;
    private BigDecimal price;
    private Double discountRate;
    private String desc;
    private List<BookComment> comments;
    private List<Order> bookOrders;

    public List<Book> getRelateBooks(){
        return new ArrayList<>();
    }

    public void preSale(Currency currency){
        this.bookStatus = BookStatus.PRE_SALE;
        this.price  = currency.getAmount();
        this.inStock = 0;
    }

    public void onSale(){
        this.bookStatus = BookStatus.IN_SALE;
        //TODO 完善上架及上货
    }

    public BigDecimal countBookRealPrice(){
        double discountRate = 0;
        if (null != this.discountRate){
            discountRate += this.discountRate * fineness.getDiscountRate();
        } else {
            discountRate += fineness.getDiscountRate();
        }
        return this.price.multiply(new BigDecimal(discountRate));
    }

    public void discountPrice(Double discountRate){
        this.discountRate = discountRate;
        this.bookStatus = BookStatus.PROMOTION;
    }

    public Integer countDealNumber(CountEnum countEnum){
        return countDealNumber(countEnum,null);
    }

    public Integer countInSellerNumber(){
        return countDealNumber(CountEnum.TOTAL, OrderStatus.WAIT_SOLD);
    }

    public Integer countDealNumber(CountEnum countEnum, OrderStatus orderStatus){
        int orderRate = null == orderStatus.getBelongType() ? 2:1;
        AtomicReference<Integer> countValues = new AtomicReference<>(0);
        bookOrders.parallelStream().filter(order -> {
            if (order.filterByDayCount(countEnum)){
                return order.getOrderStatus().equals(orderStatus);
            }
            return false;
        }).forEach(order -> {
            countValues.updateAndGet(v -> v + order.getBookNumber());
        });
        return  countValues.get()/orderRate;
    }

    public String getIsbn() {
        return isbn.replace('-',' ')
                .replaceAll(" +","");
    }
}
